import React, { Component } from "react";
import Highlighter from "react-highlight-words";
import {
  PageHeader,
  Tabs,
  Button,
  Statistic,
  Descriptions,
  Badge,
  Card,
  Space,
  Row,
  Col,
  Divider,
  Input,
} from "antd";
import { Liquid, Gauge, Line, Pie, measureTextWidth } from "@ant-design/charts";
import {
  AreaChartOutlined,
  BarChartOutlined,
  PaperClipOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import "antd/dist/antd.css";
import { PlantDetail } from "../../../services/auth";

class StorageDetail extends Component {
  constructor(props) {
    super(props);
    this.id = this.props.value.id;
    this.state = {
      searchText: "",
      searchedColumn: "",
      plant: {},
      products: [],
      storageLog: [],
      percentIndex: 0,
      timeGraph: [],
      score: 0,
    };
  }

  configRose = {
    data: this.data,
    xField: "type",
    yField: "value",
    seriesField: "type",
    radius: 0.9,
    legend: { position: "bottom" },
  };

  getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            this.handleSearch(selectedKeys, confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: "block" }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            Search
          </Button>
          <Button
            onClick={() => this.handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            Reset
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({ closeDropdown: false });
              this.setState({
                searchText: selectedKeys[0],
                searchedColumn: dataIndex,
              });
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined style={{ color: filtered ? "#1890ff" : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : "",
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select(), 100);
      }
    },
    render: (text) =>
      this.state.searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
          searchWords={[this.state.searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  componentDidMount() {
    PlantDetail(this.id).then(
      (response) => {
        console.log(response.data);
        this.setState({
          plant: response.data,
          products: response.data.productStock,
          percentIndex: response.data.storage / response.data.max_capacity,
          timeGraph: response.data.timeGraph,
          score: response.data.stockScore,
        });
      },
      (error) => {
        console.log("error");
      }
    );
  }

  render() {
    const { TabPane } = Tabs;

    const Content = ({ children, extra }) => (
      <div className="content">
        <div className="main">{children}</div>
        <div className="extra">{extra}</div>
      </div>
    );

    var ticks = [0, 1 / 3, 2 / 3, 1];
    var color = ["#F4664A", "#FAAD14", "#30BF78"];
    var config2 = {
      percent: this.state.score / 100,
      radius: 1,
      range: {
        ticks: [0, 1],
        color: ["l(0) 0:#F4664A 0.5:#FAAD14 1:#30BF78"],
      },
      indicator: {
        pointer: { style: { stroke: "#D0D0D0" } },
        pin: { style: { stroke: "#D0D0D0" } },
      },
      statistic: {
        title: {
          formatter: function formatter(_ref) {
            var percent = _ref.percent;
            if (percent < ticks[1]) {
              return "差";
            }
            if (percent < ticks[2]) {
              return "中";
            }
            return "优";
          },
          style: function style(_ref2) {
            var percent = _ref2.percent;
            return {
              fontSize: "36px",
              lineHeight: 1,
              color:
                percent < ticks[1]
                  ? color[0]
                  : percent < ticks[2]
                  ? color[1]
                  : color[2],
            };
          },
        },
        content: {
          offsetY: 36,
          style: {
            fontSize: "24px",
            color: "#4B535E",
          },
          formatter: function formatter() {
            //
            return null;
          },
        },
      },
    };

    function renderStatistic(containerWidth, text, style) {
      var _measureTextWidth = (0, measureTextWidth)(text, style),
        textWidth = _measureTextWidth.width,
        textHeight = _measureTextWidth.height;
      var R = containerWidth / 2;
      var scale = 1;
      if (containerWidth < textWidth) {
        scale = Math.min(
          Math.sqrt(
            Math.abs(
              Math.pow(R, 2) /
                (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2))
            )
          ),
          1
        );
      }
      var textStyleStr = "width:".concat(containerWidth, "px;");
      return '<div style="'
        .concat(textStyleStr, ";font-size:")
        .concat(scale, "em;line-height:")
        .concat(scale < 1 ? 1 : "inherit", ';">')
        .concat(text, "</div>");
    }

    const dataPie = [];
    this.state.products.map((product) => {
      let item = {
        type: product.produce_name,
        value: product.quantity,
      };
      dataPie.push(item);
    });

    var config = {
      appendPadding: 10,
      data: dataPie,
      angleField: "value",
      colorField: "type",
      radius: 1,
      innerRadius: 0.64,
      label: {
        type: "inner",
        offset: "-50%",
        style: { textAlign: "center", fontSize: 12 },
        autoRotate: false,
        content: "{value}",
      },
      statistic: {
        title: {
          offsetY: -4,
          style: { fontSize: "14px" },
          customHtml: function customHtml(container, view, datum) {
            var _container$getBoundin = container.getBoundingClientRect(),
              width = _container$getBoundin.width,
              height = _container$getBoundin.height;
            var d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
            var text = datum ? datum.type : "总计";
            return renderStatistic(d, text, { fontSize: 8 });
          },
        },
        content: {
          offsetY: 4,
          style: { fontSize: "32px" },
          customHtml: function customHtml(container, view, datum, data) {
            var _container$getBoundin2 = container.getBoundingClientRect(),
              width = _container$getBoundin2.width;
            var text = datum
              ? "".concat(datum.value)
              : "".concat(
                  data.reduce(function (r, d) {
                    return r + d.value;
                  }, 0)
                );
            return renderStatistic(width, text, { fontSize: 2 });
          },
        },
      },
      interactions: [
        { type: "element-selected" },
        { type: "element-active" },
        { type: "pie-statistic-active" },
      ],
    };

    return (
      <div>
        <PageHeader
          className="site-page-header-responsive"
          title={this.state.plant.name}
          subTitle={this.state.plant.id}
          footer={
            <Tabs defaultActiveKey="1">
              <TabPane tab="库存详情" key="details">
                <div style={{ marginTop: "24px" }}>
                  <Row gutter={32}>
                    <Col span={12}>
                      <Card>
                        <Row>
                          <Col span={14}>
                            <div style={{ margin: "8px 0px 8px 0px" }}>
                              <Statistic
                                title="当前库存"
                                value={this.state.plant.storage}
                                prefix={<AreaChartOutlined />}
                              />
                            </div>
                            <div style={{ margin: "16px 0px 8px 0px" }}>
                              <Statistic
                                title="库存容量"
                                value={this.state.plant.max_capacity}
                                prefix={<BarChartOutlined />}
                              />
                            </div>
                          </Col>
                          <Col span={10}>
                            <div>
                              <Liquid
                                {...{
                                  percent: this.state.percentIndex,
                                  outline: {
                                    border: 4,
                                    distance: 8,
                                  },
                                  wave: { length: 128 },
                                }}
                                height={150}
                                width={150}
                              />
                            </div>
                          </Col>
                        </Row>
                      </Card>
                    </Col>

                    <Col span={12}>
                      <Card>
                        <Row>
                          <Col span={10}>
                            <div style={{ marginTop: "48px" }}>
                              <Statistic
                                title="库存得分"
                                value={this.state.score.toFixed(2)}
                                prefix={<PaperClipOutlined />}
                              />
                            </div>
                          </Col>
                          <Col span={14}>
                            <Gauge {...config2} height={150} width={150} />
                          </Col>
                        </Row>
                      </Card>
                    </Col>
                  </Row>
                </div>
                <Divider />
                <div>
                  <Row gutter={36}>
                    <Col span={16}>
                      <Card>
                        <Line
                          {...{
                            data: this.state.timeGraph,
                            xField: "time",
                            yField: "count",
                            seriesField: "name",
                            yAxis: {
                              label: {
                                formatter: function formatter(v) {
                                  return "".concat(v);
                                },
                              },
                            },
                            legend: { position: "top" },
                            smooth: true,
                            animation: {
                              appear: {
                                animation: "path-in",
                                duration: 5000,
                              },
                            },
                          }}
                        />
                      </Card>
                    </Col>
                    <Col span={8}>
                      <Card bordered={false} title="详情">
                        <Pie {...config} width={300} height={300} />
                      </Card>
                    </Col>
                  </Row>
                </div>
              </TabPane>
            </Tabs>
          }
        >
          <Content>
            {
              <Descriptions bordered size="default" column={2}>
                <Descriptions.Item
                  label="负责人"
                  contentStyle={{ fontWeight: "bold" }}
                >
                  {this.state.plant.manager}
                </Descriptions.Item>
                <Descriptions.Item
                  label="工厂编号"
                  contentStyle={{ fontWeight: "bold", color: "black" }}
                >
                  <a>{this.state.plant.code}</a>
                </Descriptions.Item>
                <Descriptions.Item
                  label="销售区域"
                  contentStyle={{ fontWeight: "bold" }}
                >
                  {this.state.plant.saleorg_name}
                </Descriptions.Item>
                <Descriptions.Item
                  label="运行状态"
                  contentStyle={{ fontWeight: "bold" }}
                >
                  <Badge status="success" text={"运行中"} />
                </Descriptions.Item>
                <Descriptions.Item
                  label="地址"
                  contentStyle={{ fontWeight: "bold" }}
                >
                  {this.state.plant.address}
                </Descriptions.Item>
              </Descriptions>
            }
          </Content>
        </PageHeader>
      </div>
    );
  }
}

export default StorageDetail;
